/**
 * Created by J on 2017/1/3.
 */
(function (angular) {
	//封装服务
	//通过localStorage保存数据
	var app=angular.module('todoApp.service',[]);
	app.service('storageService',['$filter',function ($filter) {
		//获取到当前在localStorage中的数据
		 var todoList=JSON.parse(localStorage.getItem('todoList')||'[]');
		//获取随机数
		function getID() {
			return Math.random();
		}
		//获取数据
		this.getTodoList=function () {
			return  todoList;
		};
		//添加todo
		this.addTodo=function (text) {
			// $scope.todoList.push({id:getID(),text:$scope.todoText,status:false});
			todoList.push({id:getID(),text:text,status:false});
			//保存到localStorage中
			this.saveTodo();
		};
		//删除todo
		this.delTodo=function (todo) {
			//找到当前的下标
			var index=todoList.indexOf(todo);
			//根据下标删除某一个todo
			todoList.splice(index,1);
			//保存到localStorage中
			this.saveTodo();
			return todoList;
		};
		//保存数据
		this.saveTodo=function () {
		  localStorage.setItem('todoList',JSON.stringify(todoList));
		};
		//修改数据并保存
		this.editTodo=function (todos) {
			//保存到localStorage
			localStorage.setItem('todoList',JSON.stringify(todos));
			todoList=todos;
			return todos;
		};
		//清除已完成数据
		this.clearCompleted=function () {
			 todoList=$filter('filter')(todoList,{status:false});
			 this.saveTodo();
			 return todoList;
		};
		//全选功能
		this.changeToggleAll=function (status) {
			 todoList.forEach(function (item) {
				item.status=status;
			});
			this.saveTodo();
			return todoList;
		};
		//测试
		//this.test='storageService'

	}])
})(angular);
